package com.kit;

public class ByteUtil {
	// BIN、OCT、HEX、DEC分别代表二、八、十六、十进制、
	private final static String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	public static byte[] hex2byte(String strhex) {
		if (strhex == null)
			return null;
		int l = strhex.length();
		if (l % 2 == 1)
			return null;
		byte[] b = new byte[l / 2];
		for (int i = 0; i != l / 2; i++)
			b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
		return b;
	}
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}
	public static int byte2int(byte[] bytes) {
		return (bytes[0] & 0xff) << 24 | (bytes[1] & 0xff) << 16 | (bytes[2] & 0xff) << 8 | (bytes[3] & 0xff);
	}

	public static byte[] int2byte(int num) {
		byte[] bytes = new byte[4];
		bytes[0] = (byte) ((num >> 24) & 0xff);
		bytes[1] = (byte) ((num >> 16) & 0xff);
		bytes[2] = (byte) ((num >> 8) & 0xff);
		bytes[3] = (byte) (num & 0xff);
		return bytes;
	}
	/**
	 * 10进制转化成其他进制
	 */
	public static String dec2oher(long num, int jz) {
		String str = "";
		if (num == 0) {
			return "";
		} else {
			str = dec2oher(num / jz, jz);
			return str + chars.charAt((int) (num % jz));
		}
	}

	/**
	 * 其他进制转化成10进制
	 */
	public static long oher2dec(String str, int jz) {
		long result = 0;
		int len = str.length();
		for (int i = len; i > 0; i--)
			result += chars.indexOf(str.charAt(i - 1)) * ((long) (Math.pow(jz, len - i)));
		return result;
	}
}
